package com.pan.crawler.impl4;

import com.pan.crawler.Directory;
import com.pan.entity.BookDirectory;
import com.pan.entity.Chapter;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.edge.EdgeDriver;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class DirectoryImpl4 implements Directory {

    private String website = "www.108shu.com";

    public void checkUrl(String url){
        String websiteRegex = website;
        Pattern pattern = Pattern.compile(websiteRegex);
        Matcher matcher = pattern.matcher(url);
        if (!matcher.find()){
            throw new RuntimeException("网站错误："+url+"，应该为："+website);
        }
    }

    @Override
    public BookDirectory get(String url) {
        checkUrl(url);
        EdgeDriver edgeDriver = new EdgeDriver();
        edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
        edgeDriver.navigate().to(url);
        String bookName = edgeDriver.findElement(By.className("top"))
                .findElement(By.cssSelector("h1")).getText();

        List<Chapter> chapterList = new ArrayList<>();
        int[] i = new int[]{0};

        List<WebElement> optionList = edgeDriver.findElement(By.cssSelector("select")).findElements(By.cssSelector("option"));
        List<String> directoryUrlList = optionList.stream().map(option -> option.getAttribute("value")).collect(Collectors.toList());
        directoryUrlList.forEach(directoryUrl->{
            edgeDriver.manage().timeouts().implicitlyWait(Duration.ofSeconds(5));
            edgeDriver.navigate().to(directoryUrl);
            List<WebElement> aList = edgeDriver.findElements(By.className("section-box")).get(1).findElements(By.cssSelector("a"));
            chapterList.addAll(aList.stream().map(a->{
                String title = a.getText();
                String chapterUrl = a.getAttribute("href");
                return new Chapter().setTitle(title).setUrl(chapterUrl).setId(i[0]++);
            }).collect(Collectors.toList()));
        });
        edgeDriver.quit();
        return new BookDirectory().setBookName(bookName).setChapterList(chapterList);
    }
}
